<?php
/**
 * @file
 *
 * Page callback function for dmin/service/ajax-users/action/% menu path
 * grid ajax action response
 * 
 * @param  $action
 */
function extjs_grid_users_response_callback($action)
{
	//@todo multisort case
	$actions = array(
		'read',
		'create',
		'destroy',
		'update',
		'validation'
	);
	if(in_array($action, $actions))
	{
		$postData = json_decode(file_get_contents('php://input'));//get extjs request body
		$fieldsArr = array(
			'table' => 'users', 
			'fields' => array(
				//'uid' => 'uid',
				'user_mail' => 'mail',
				'user_name' => 'name',
				'user_created' => 'created',
				'user_status' => array('name' => 'status', 'type' => 'checkbox')
			),
		);
		if($action == 'validation'){
			$name = !empty($_POST['username']) ? $_POST['username'] : '';
			//server valiation 
			if($name && _fields_validation('name', $name, 'unique')){
				echo json_encode(array('success' => false, 'msg' => 'User name must be unique.'));
				//return;
			}
			else{
				echo json_encode(array('success' => true));
			}
		}
		elseif($action == 'read')
		{
			$sortArr = !empty($_REQUEST['sort']) ? json_decode($_REQUEST['sort']) : null;
			$fieldSortObj = is_array($sortArr) ? $sortArr[0] : null;//get first field sort (ignore multisort case)

			$sfield = $fieldSortObj && !empty($fieldSortObj->property) ? $fieldSortObj->property : 'uid';
			$sorder = $fieldSortObj && !empty($fieldSortObj->direction) ? $fieldSortObj->direction : 'ASC';

			$start = !empty($_REQUEST['start']) ? $_REQUEST['start'] : 0;
			$limit = !empty($_REQUEST['limit']) ? $_REQUEST['limit'] : GRID_DEFAULT_COUNT;

			echo json_encode(get_users($sfield, $sorder, $start, $limit));
		}
		elseif ($action == 'create' || $action == 'update'){
			//validation
			$userPostData = !empty($postData->users) ? (is_array($postData->users) ? end($postData->users) : $postData->users) : array();//if array get last effected
			//@todo 
			$userDbData = array();//adjusted to users table array
			foreach((array)$userPostData as $f => $v)//$f = alias $v = value
			{
				if(array_key_exists($f, $fieldsArr['fields'])){
					/*
					 * in case of checkbox field type
					 * @todo make it in js
					 */
					if(is_array($fieldsArr['fields'][$f])){
						$alias = $fieldsArr['fields'][$f];
						if($alias['type'] == 'checkbox'){
							$userDbData[$fieldsArr['fields'][$f]['name']] = (int)$v;
						}
					}else{
						$userDbData[$fieldsArr['fields'][$f]] = $v;
					}
				}
			}
			if(isset($userPostData->user_status)){
				$userPostData->user_status = (int)$userPostData->user_status;
			}
			//@todo make js solution for checkox correct(0/1) responce
			$userResponseData = array_intersect_key((array)$userPostData, $fieldsArr['fields']);
			if ($action == 'create')
			{
				if($userDbData){
					//$uid = drupal_write_record($fieldsArr['table'], $userDbData, array('uid'));		
//					$uid = db_insert($fieldsArr['table']) // Table name no longer needs {}
//						->fields($userDbData)
//						->execute();
					//var_dump($userDbData); exit;
					$user = user_save(null, $userDbData);
					if($user){
						echo json_encode(array('success' => true, 'users' => array_merge($userResponseData, array('uid' => $user->uid)), 'msg' => sprintf(USER_CALLBACK_MSG_SUCCESS_TPL, 'created')));
					}else{
						echo json_encode(array('success' => false, 'msg' => sprintf(USER_CALLBACK_MSG_ERROR_NO_DATA_TPL, 'created')));
					}	
				}
				else{
					echo json_encode(array('success' => false, 'msg' => sprintf(USER_CALLBACK_MSG_ERROR_NO_DATA_TPL, 'created')));
				}
			}	
			elseif ($action == 'update')
			{
				//update action
				if($userDbData && !empty($userPostData->uid)){		
					$num_updated = db_update($fieldsArr['table']) // Table name no longer needs {}
						->fields($userDbData)
						->condition('uid', $userPostData->uid, '=')
						->execute();
					if($num_updated){
						echo json_encode(array('success' => true, 'users' => $userResponseData, 'msg' => sprintf(USER_CALLBACK_MSG_SUCCESS_TPL, 'updated')));
					}else{
						echo json_encode(array('success' => false, 'msg' => sprintf(USER_CALLBACK_MSG_ERROR_NO_DATA_TPL, 'updated')));
					}	
				}
				else{
					echo json_encode(array('success' => false, 'msg' => sprintf(USER_CALLBACK_MSG_ERROR_NO_DATA_TPL, 'updated')));
				}
			}
		}		
		elseif ($action == 'destroy')
		{
			$userPostData = !empty($postData->users) ? (is_array($postData->users) ? end($postData->users) : $postData->users) : array();//if array get last effected
			$uid = !empty($userPostData->uid) ? $userPostData->uid : null;
			
			if($uid)
			{
//				$num_deleted = db_delete('users')->
//					where('uid=:uid', array(':uid' => $uid))->
//					//== condition('uid', $uid)
//					execute();
				user_delete($uid);
				echo json_encode(array('success' => true, 'msg' => sprintf(USER_CALLBACK_MSG_SUCCESS_TPL, 'deleted')));
			}
			else 
			{
				echo json_encode(array('success' => false, 'msg' => sprintf(USER_CALLBACK_MSG_ERROR_TPL, 'deleted') . ' Unset user id.'));
			}
		}
		//ajax fields validation
		elseif($action == 'validation'){
			
		}
		else 
		{
			echo json_encode(array('result' => 'error', 'msg' => 'No such action.'));
		}		
	}
}

/**
 * get users(username, email)
 */
function get_users($sfield = 'uid', $sorder = 'ASC', $start = 0, $limit = GRID_DEFAULT_COUNT)
{
//var_dump(array(':sfield' => $sfield, ':sorder' => $sorder)); exit;
	/*
	$result = db_query_range(
		'SELECT users.uid AS uid, users.mail AS user_mail,	users.name AS user_name, users.created AS user_created
		 FROM {users} users 
		 WHERE uid != 0
		 ORDER BY :sfield :sorder',
		 $start, $limit, array(':sfield' => $sfield, ':sorder' => $sorder)
	);
*/
	//drupal7 query, no way to set alise in method fields only with addField
	$fieldsArr = array('table' => 'users', 
		'fields' => array(
			'uid' => 'uid',
			'mail' => 'user_mail',
			'name' => 'user_name',
			'created' => 'user_created',
			'status' => 'user_status'
		)
	);
	$query = db_select('users', 'users');
	foreach($fieldsArr['fields'] as $field => $alias)
	{
		$query->addField($fieldsArr['table'], $field, $alias);
	}
	$query->where('uid != 0')->
		    orderBy($sfield, $sorder)->
			range($start, $limit);	 
	$result = $query->execute();		 
	
	return array('users' => _format_users($result->fetchAll(), FORMAT_ASSOC), 'total' => get_users_number());
}

function extjs_grid_users_fields_validation_response_callback()
{
	//server valiation
	if(_fields_validation('name', $userDbData['name'], 'unique')){
		echo json_encode(array('success' => true, 'msg' => sprintf(USER_CALLBACK_MSG_SUCCESS_TPL, 'updated')));
	}
}

/**
 * 
 * validate grid field
 * 
 * @param  $field
 * @param $val
 * @param validType
 */
function _fields_validation($field, $val, $validType)
{
	$errors = array();
	$userFields = array(
				'table' => 'users', 
				'fields' => array(
					//'uid' => 'uid',
					'mail',
					'name',
					'created',
					'status'
				)
			);
	$validTypes = array(
		'unique', 
		'empty'
		//...
	);
	if(in_array($validType, $validTypes) && in_array($field, $userFields['fields'])){
		if($validType == 'unique'){
			return db_query("SELECT count(uid) FROM {users} where `{$field}`=:val", array(':val' => $val))->fetchField();
		}
		if($validType == 'empty'){
			return (bool)$val;
		}
	}
}


/**
 * 
 */
function extjs_grid_page_callback()
{
	drupal_add_js(drupal_get_path('module', 'extjs_grid') . '/js/grid.js');
	drupal_add_css(drupal_get_path('module', 'extjs_grid') . '/css/grid.css');
		
	return theme('extjs_grid', array());
}

function get_users_number($options = array())
{
	return db_query('SELECT count(users.uid) FROM {users} users WHERE uid != 0')->fetchField();
}

function _format_users($users, $format = FORMAT_ASSOC)
{
	if($format == FORMAT_ASSOC)
	{
		array_walk($users, function(&$row) {
    		$row = (array)$row;
  		});	
  		
		return $users;
	}
	elseif(empty($format) || $format == FORMAT_OBJECT)
	{
		return $users;
	}
}
